<template>
  <el-dialog v-model="dialogFormVisible" :title='props.Messagetitle' width="50%" align-center append-to-body
    :destroy-on-close='true'>
    <div class="dialog-content">
      <el-form :model="formData" label-width="120px" style="max-width: 600px;" :rules="rules"
        :label-position="labelPosition">
        <el-form-item label="主题" prop='message_title'>
          <el-input v-model="formData.message_title" />
        </el-form-item>
        <el-form-item label="发布部门" prop='message_publish_department'>
          <el-input v-if="user_department" v-model="user_department" disabled></el-input>
          <el-select v-else  v-model="formData.message_publish_department" placeholder="请选择发布部门" >
            <el-option v-for="item in options" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="发布人" prop='message_publish_name'>
          <el-input v-model="formData.message_publish_name" disabled />
        </el-form-item>
        <el-form-item label="接收部门" prop='message_receipt_object'>
          <el-select v-model="formData.message_receipt_object" placeholder="请选择接收部门">
            <el-option v-for="item in allOptions" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="公告等级" prop='message_level'>
          <el-select v-model="formData.message_level" placeholder="选择公告等级">
            <el-option label="一般" value="一般" />
            <el-option label="重要" value="重要" />
            <el-option label="必要" value="必要" />
          </el-select>
        </el-form-item>
        <el-form-item label="内容" prop='message_content'>
          <div style="border: 1px solid #ccc">
            <!-- wangEditor结构 -->
            <Toolbar style="border-bottom: 1px solid #ccc;width: 600px;" :editor="editorRef"
              :defaultConfig="toolbarConfig" :mode="mode" />
            <Editor style="height: 300px; overflow-y: hidden;width: 600px;" v-model="valueHtml"
              :defaultConfig="editorConfig" :mode="mode" @onCreated="handleCreated" />
          </div>
        </el-form-item>

      </el-form>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="submitMessage">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { onBeforeUnmount, reactive, ref, shallowRef } from 'vue'
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { ElMessage } from 'element-plus'
import { publishMessageAPI, editMessageAPI } from '../../../api/message'
import { tracking } from '../../../utils/operate'
import { getCompanyDepartment } from '../../../api/setting'
import { addDepartmentMsgAPI } from '../../../api/department_msg'




const labelPosition = ref('left')

// 弹窗开关
const dialogFormVisible = ref(false)

// 不包括全体成员
const options = ref()
// 包括全体成员
const allOptions = ref()



const props = defineProps<{
  getCompanyMessageByPager: Function,
  Messagetitle: string,
  getSystemMessageByPager: Function
}>()


interface FormData {
  id: number;
  message_title: string;
  message_publish_department: string;
  message_publish_name: string;
  message_category: string;
  message_receipt_object: string;
  message_level: string;
  message_content: string;
}

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
// mode
const mode = ref('default')
// 内容 HTML
const valueHtml = ref()
// 工具栏
const toolbarConfig = {
  excludeKeys: [] as string[]
}
// 上传图片，修改 uploadImage 菜单配置
const editorConfig = {
  placeholder: '',
  MENU_CONF: {
    // uploadImage: {
    //   //上传图片配置
    //   server: 'http://127.0.0.1:3007/set/uploadCompanyPicture', //上传接口地址
    //   fieldName: 'file', //上传文件名
    //   methods: 'post',
    //   metaWithUrl: true, // 参数拼接到 url 上
    //   // 单个文件上传成功之后
    //   // onSuccess(file, res) {
    //   // },
    //   // 自定义插入图片
    //   customInsert(res, insertFn) {
    //     insertFn(res.url)
    //   },
    // },
  }
}

// 排除菜单组，写菜单组 key 的值即可
toolbarConfig.excludeKeys = [
  'blockquote',
  'bgColor',
  'color',
  'group-more-style',
  'fontFamily',
  'bulletedList',
  'numberedList',
  'lineHeight',
  'todo',
  'emotion',
  'insertLink',
  'group-video',
  'insertTable',
  'codeBlock',
  'divider',
  'fullScreen'
]

let user_department = localStorage.getItem('userinfo') as string ? JSON.parse(localStorage.getItem('userinfo') as string).department : ''

// 表单数据
const formData: FormData = reactive({
  id: 0,
  message_title: '',
  message_publish_department: user_department ? user_department : '',
  message_publish_name: JSON.parse(localStorage.getItem('userinfo') as string).name,
  message_category: '',
  message_receipt_object: '',
  message_level: '',
  message_content: '',
})



const rules = reactive({
  message_title: [
    { required: true, message: '请输入公告标题', trigger: 'blur' },
  ],
  message_publish_department: [
    { required: true, message: '请选择发布部门', trigger: 'blur' },
  ],
  message_publish_name: [
    { required: true, message: '请输入发布人', trigger: 'blur' },
  ],
  message_receipt_object: [
    { required: true, message: '请选择的接收对象', trigger: 'blur' },
  ],
  message_level: [
    { required: true, message: '请选择公告等级', trigger: 'blur' },
  ],
  message_content: [
    { required: true, message: '请输入公告内容', trigger: 'blur' },
  ],
})



// 部门数据
const returnDepartment = async () => {
  const res = await getCompanyDepartment()
  const arr: any = Array.from(JSON.parse(res.data.data))
  options.value = arr
  allOptions.value = arr.concat('全体成员')
}
returnDepartment()

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor: any) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

const department = JSON.parse(localStorage.getItem('userinfo') as string)?.department

// 点击确定 新增 or 编辑 
const submitMessage = async () => {
  if (props.Messagetitle == '发布公司公告') {
    formData.message_category = '公司公告'
    formData.message_content = valueHtml.value
    const res = await publishMessageAPI(formData)
    if (res.data.status === 0) {
      props.getCompanyMessageByPager()
      const readId = res.data.id
      await addDepartmentMsgAPI({ readId, department })
      dialogFormVisible.value = false
      ElMessage.success('发布公司公告成功')
      tracking("消息管理", "发布公司公告", { title: formData.message_title }, "中级")
    } else {
      ElMessage.error('发布公司公告失败')
    }
  }
  if (props.Messagetitle == '编辑公司公告') {
    formData.message_content = valueHtml.value
    const res = await editMessageAPI(formData)
    if (res.data.status === 0) {
      props.getCompanyMessageByPager()
      const readId = res.data.id
      await addDepartmentMsgAPI({ readId, department })
      dialogFormVisible.value = false
      ElMessage.success('编辑公司公告成功')
      tracking("消息管理", "编辑公司公告", { title: formData.message_title }, "中级")
    } else {
      ElMessage.error('编辑公司公告失败')
    }
  }
  if (props.Messagetitle == '发布系统消息') {
    formData.message_category = '系统消息'
    formData.message_content = valueHtml.value
    const res = await publishMessageAPI(formData)
    if (res.data.status === 0) {
      props.getSystemMessageByPager()
      const readId = res.data.id
      await addDepartmentMsgAPI({ readId, department })
      dialogFormVisible.value = false
      ElMessage.success('发布系统消息成功')
      tracking("消息管理", "发布系统消息", { title: formData.message_title }, "中级")
    } else {
      ElMessage.error('发布系统消息失败')
    }

  }
  if (props.Messagetitle == '编辑系统消息') {
    formData.message_content = valueHtml.value
    const res = await editMessageAPI(formData)
    if (res.data.status === 0) {
      props.getSystemMessageByPager()
      const readId = res.data.id
      
      await addDepartmentMsgAPI({ readId, department })
      dialogFormVisible.value = false
      ElMessage.success('编辑系统消息成功')
      tracking("消息管理", "编辑系统消息", { title: formData.message_title }, "中级")
    } else {
      ElMessage.error('编辑系统消息失败')
    }
  }
}




// 打开编辑管理员的弹窗
const open = (row) => {
  if (row) {
    formData.id = row.id,
      formData.message_title = row.message_title,
      formData.message_publish_department = row.message_publish_department,
      formData.message_category = row.message_category,
      formData.message_receipt_object = row.message_receipt_object,
      formData.message_level = row.message_level,
      valueHtml.value = row.message_content
  }
  dialogFormVisible.value = true
}


defineExpose({
  open
})


</script>

<style lang="scss" scoped>
.dialog-content {
  display: flex;
  padding: 20px 30px;
  flex: 1;
  max-height: 800px;
  overflow: auto;
}

.el-dialog__body {
  padding: 0;
}

.el-input {
  width: 240px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.el-form-item {
  margin: 16px;
}

:deep(.w-e-text-container p) {
  margin: 0;
}

:deep(.el-select) {
  width: 240px;
}
</style>